<template>
  <div>
    <ul>
      <li v-for="item of msgList" :key="item.id">
        <p>
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.dateTime) }}</span>
        <p>{{ item.msg }}</p>
        </p>
      </li>
    </ul>
    <input type="text" placeholder="请输入消息" v-model="msg">
    <button @click='handleSendBtnClick'>发送</button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
interface MessageList {
  id: string
  user: string
  dateTime: Date
  msg: string
}
const msg = ref('')
const msgList = reactive<MessageList[]>([])
let username: string = ''
onMounted(() => {
  if (localStorage.getItem('username')) {
    username = localStorage.getItem('username')!;
  }
})





const ws = new WebSocket('ws://localhost:8000')


const handleWsOpen = (e: Event) => {
  console.log('FE:WsOpen', e);
}
const handleWsClose = (e: CloseEvent) => {
  ws.send(JSON.stringify({
    id: new Date().getTime + '',
    user: username,
    dateTime: new Date(),
    msg: '关闭'
  }))
  console.log('FE:WsClose', e);
}
const handleWsError = (e: Event) => {
  console.log('FE:WsError', e);
}
const handleWsMessage = (e: MessageEvent) => {
  console.log('FE:WsMessage', e);
  console.log(JSON.parse(e.data));
  msgList.push(JSON.parse(e.data))
}

ws.addEventListener('open', handleWsOpen.bind(this), false)
ws.addEventListener('close', handleWsClose.bind(this), false)
ws.addEventListener('error', handleWsError.bind(this), false)
ws.addEventListener('message', handleWsMessage.bind(this), false)





const handleSendBtnClick = () => {
  console.log(msg.value);
  ws.send(JSON.stringify({
    id: new Date().getTime + '',
    user: username,
    dateTime: new Date(),
    msg: msg.value
  }))
  msg.value = ''
}


</script>

<style scoped>

</style>